<?php

namespace yunj\app\admin\controller\auth;

use think\db\Query;
use think\facade\Db;
use yunj\app\admin\controller\Controller;
use yunj\app\admin\enum\auth\AuthPageType;
use yunj\app\admin\enum\auth\AuthType;
use yunj\app\admin\enum\EnableLoginAuth;
use yunj\app\admin\enum\State;
use yunj\app\admin\service\auth\AuthPageService;
use yunj\app\admin\service\auth\AuthService;
use yunj\app\admin\service\route\RouteRequestService;
use yunj\core\builder\YunjForm;
use yunj\core\enum\TipsTemplet;

class AuthController extends Controller {

    /**
     * @return AuthPageService
     */
    private function getService(): AuthPageService {
        return app(AuthPageService::class);
    }

    public function lists() {
        $builder = $this->getService()->getListBuilder();
        $builder->assign();
        return view_table($builder);
    }

    public function add() {
        $builder = $this->getService()->getFormBuilder(false, request()->param('isAddChild') == 'yes');
        $builder->assign();
        return $this->view('auth/form', ['builderId' => $builder->getId()]);
    }

    public function edit() {
        $builder = $this->getService()->getFormBuilder(true);
        $builder->assign();
        return $this->view('auth/form', ['builderId' => $builder->getId()]);
    }

    public function sort() {
        $pageType = request()->param('pageType');
        if (!AuthPageType::isValue($pageType)) {
            return request()->isAjax() ? redirect_tips(TipsTemplet::ERROR, '异常访问') : error_json('异常访问');
        }
        /** @var AuthPageType $pageTypeObj */
        $pageTypeObj = AuthPageType::byValue($pageType);
        $args = [
            'field' => function (YunjForm $builder) {
                return [
                    "sort_tree" => [
                        "title" => "排序",
                        "type" => "tree",
                        "mode" => "edit",
                        "dragSort" => "level",
                        "nodeIdKey" => "key",
                        "nodePidKey" => "parent",
                    ]
                ];
            },
            'button' => function ($builder) {
                return ['reset', 'submit'];
            },
            'load' => function (YunjForm $builder) use ($pageTypeObj) {
                if (!$pageTypeObj) {
                    return [];
                }
                $where = [['state', '=', State::NORMAL]];
                if ($pageTypeObj->isMenu()) {
                    $where[] = ['type', '=', $pageTypeObj->getDbType()];
                }
                $order = [
                    ($pageTypeObj->isMenu() ? 'menu_sort' : 'sort') => 'asc',
                    'is_system' => 'asc'
                ];
                $items = self::getAdminAuthModel()->getOwnRowsToArray($where, ['`key`', 'parent', 'name'], $order);
                $items = array_map(function ($item) {
                    $item['name'] = "【{$item['name']}】{$item['key']}";
                    return $item;
                }, $items);
                return ['sort_tree' => $items];
            },
            'submit' => function (YunjForm $builder, array $data) use ($pageTypeObj) {
                $datas = [];
                $sort = 0;
                $sortKey = $pageTypeObj->isMenu() ? 'menu_sort' : 'sort';
                foreach ($data['sort_tree'] as $v) {
                    $datas[] = [
                        'key' => $v['key'],
                        $sortKey => $sort++,
                    ];
                }
                self::getAdminAuthModel()->batchChange($datas);
                // 清理缓存
                AuthService::clearCache();
                return success_json(['reload' => true]);
            }
        ];
        $builder = YF('AuthSort', $args);
        return view_form($builder);
    }

    // 下拉搜索
    public function dropdownsearch() {
        $data = input('get.');
        // 输入关键字
        $keywords = $data['keywords'];
        // 使用 , 分割的初始值
        $keys = $data['keys'];
        // 进行数据查询
        $where = [
            ['state', '=', State::NORMAL],
        ];
        if ($keywords) {
            $where[] = ['key|full_name', 'like', "%{$keywords}%"];
        }
        if ($keys) {
            $where[] = ['key', 'in', strstr($keys, ',') ? $keys : [$keys]];
        }
        $field = ['key', 'full_name'];
        $datas = self::getAdminAuthModel()->getOwnRowsToArray($where, $field, [], 1, 20);
        $items = [];
        foreach ($datas as $v) {
            $txt = $v['key'] . "【{$v['full_name']}】";
            $items[] = ['key'=>$v['key'],'name'=>$txt];
        }
        // 返回数据
        return success_json($items);
    }

    // 路由请求项的下拉搜索
    public function requestDropdownsearch() {
        $data = input('get.');
        // 输入关键字
        $keywords = $data['keywords'];
        // 使用 , 分割的初始值
        $ids = $data['ids'];
        // 进行数据查询
        $where = [
            ['state', '=', State::NORMAL],
        ];
        if ($keywords) $where[] = ['full_desc', 'like', "%{$keywords}%"];
        if ($ids) {
            $where[] = ['id', 'in', $ids];
        } else {
            // 排除已经配置权限的路由请求项
            $where[] = function ($query) {
                /** @var Query $query */
                $query->whereNotExists(function ($subQuery) {
                    /** @var Query $subQuery */
                    $subQuery->name('admin_auth')->alias('a')
                        ->field(Db::raw(1))
                        ->whereRaw('a.request_id = id');
                });
            };
        }
        $field = ['id', 'method'];
        $datas = self::getAdminRouteRequestModel()->getOwnRowsToArray($where, $field, [], 1, 20);
        $items = [];
        foreach ($datas as $v) {
            $id = $v['id'];
            $request = RouteRequestService::getRouteRequestDataById($id);
            // 分组 名称/Key - 登录鉴权:是 - 请求日志记录:是 - 响应JSON结果日志记录:是 - baseUrl
            $name = "【" . ($v['method'] ?: 'ANY') . "】" . $request['route_base_url'] . "【{$request['full_desc']}】";
            if (EnableLoginAuth::isValue($request['enable_login_auth'])) {
                /** @var EnableLoginAuth $enableLoginAuthObj */
                $enableLoginAuthObj = EnableLoginAuth::byValue($request['enable_login_auth']);
                if (EnableLoginAuth::ON == $enableLoginAuthObj->getDesc()) {
                    $name .= "【登录鉴权】";
                }
            }
            $items[] = ['id'=>$id,'name'=>$name];
        }
        // 返回数据
        return success_json($items);
    }

}